import { Vector3, Matrix4 } from "three";
import Geo from "../gameObject/Geo.js";
import Mat from "../gameObject/Mat.js";
import Mesh from "./Mesh";
import Geography from "../../component/Geography.js";
import MeshLD from "./MeshLD";

//球体(用于等距圆柱贴图的球体)
export default class ZoomMesh extends MeshLD {

    public r: number;
    public widthSegments: number;
    public heightSegments: number;


    constructor(name: string, r: number = 0.1, widthSegments: number = 16, heightSegments: number = 16) {


        const normals: number[] = [];
        const vertices: number[] = [];
        const elements: number[] = [];
        const [width, height] = [widthSegments + 1, heightSegments + 2];

        const perW = 360 / widthSegments;
        const perH = 180 / (heightSegments + 1);

        const geography = new Geography(r, 0, 0);

        const jd = -90 * Math.PI / 180;

        for (let i = 0; i < height; i++) {
            let phi = (90 - perH * i) * Math.PI / 180;
            for (let j = 0; j < width; j++) {
                let theta = (perW * j + 180) * Math.PI / 180;
                const posi = geography.getPosition(theta, phi);
                const posi1 = posi.applyMatrix4(new Matrix4().makeRotationY(jd));

                vertices.push(...posi1);
                normals.push(...posi1.normalize());

                if (i > 0 && j > 0) {
                    const lt = (i - 1) * width + (j - 1);
                    const rt = (i - 1) * width + j;
                    const lb = (i * width) + (j - 1);
                    const rb = (i * width) + j
                    elements.push(lt, lb, rb, lt, rb, rt);
                }

            }
        }


        const geo = new Geo({
            data: {
                'a_Position': { size: 3, array: new Float32Array(vertices) },
                'a_Normal': { size: 3, array: new Float32Array(normals) },
            },
            element: { array: new Uint16Array(elements) }
        });
        const mat = new Mat({
            program: 'zoom',
            mode: ['TRIANGLES'],
            data: {
                'u_PvM4': { type: 'uniformMatrix4fv', value: new Matrix4().elements },
                'u_ModelM4': { type: 'uniformMatrix4fv', value: new Matrix4().elements },
                'u_EyeDir': { type: 'uniform3fv', value: [...new Vector3(0, 5, 0).sub(new Vector3(0, 0, 0))] },
            },
        });

        super(name, { geo: geo, mat: mat });
        this.setUniform('u_PvM4', { value: this.pvM4.elements });

        this.r = r;
        this.widthSegments = widthSegments;
        this.heightSegments = heightSegments;

    }

    public setTextureDraw(texture: any) {
        const { gl } = this;
        this.addTexureNew(gl, { 'u_Sampler': { texture: texture } });
    }


}